import { defineStore } from 'pinia';

export const useUserInfoStore = defineStore('userInfo', {
  state: () => ({
    // 用户信息状态
    userInfo: {
      real_name: '管理员',
      avatar: ''
    },
    isLoggedIn: false
  }),

  getters: {
    // 获取用户头像，有默认值
    avatar: (state) => {
      if (state.userInfo.avatar && state.userInfo.avatar.trim()) {
        return state.userInfo.avatar.replace(/`/g, '');
      }
      return '@/assets/images/favicon.png';
    },
    
    // 获取用户名
    username: (state) => {
      return state.userInfo.real_name || '管理员';
    }
  },

  actions: {
    // 从localStorage加载用户信息
    loadUserInfo() {
      try {
        const storedInfo = localStorage.getItem('userInfo');
        if (storedInfo && storedInfo.length > 0) {
          this.userInfo = JSON.parse(storedInfo);
          this.isLoggedIn = true;
        }
      } catch (error) {
        console.error('加载用户信息失败:', error);
      }
    },

    // 更新用户头像
    updateAvatar(avatarUrl) {
      this.userInfo.avatar = avatarUrl;
      // 同时更新localStorage
      this.saveToLocalStorage();
    },

    // 更新完整用户信息
    updateUserInfo(info) {
      this.userInfo = { ...this.userInfo, ...info };
      this.isLoggedIn = true;
      // 同时更新localStorage
      this.saveToLocalStorage();
    },

    // 保存到localStorage
    saveToLocalStorage() {
      try {
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo));
      } catch (error) {
        console.error('保存用户信息失败:', error);
      }
    },

    // 登出，清除用户信息
    logout() {
      this.userInfo = {
        real_name: '管理员',
        avatar: ''
      };
      this.isLoggedIn = false;
      localStorage.removeItem('userInfo');
      localStorage.removeItem('token');
    }
  }
});